package com.jt.deepSeaMain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jt.dto.CollectParamsDto;
import com.jt.pojo.*;
import com.jt.service.PhotoService;
import com.jt.utils.HttpPostAndGetUtil;
import com.jt.utils.OkhttpUtil;
import com.jt.utils.RedisUtils;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class HttpURLConnectionGetResult {
    @Autowired
    private HttpPostAndGetUtil httpPostAndGetUtil;

    @Autowired
    private OkhttpUtil okhttpUtil;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PhotoService photoService;

    @Value("${http.token.url}")
    private String tokenUrl;

    @Value("${http.CollectData.CollectDataUrl}")
    private String CollectDataUrl;

    @Value("${http.token.tokenDefalt}")
    private String tokenDefalt;

    @Value("${http.token.username}")
    private String username;

    @Value("${http.token.password}")
    private String password;

    @Value("${http.photo.photoUrl}")
    private String photoUrl;

    /*获取深海token*/
    public Result getToken() {
        String res = "";
        try {
//            String pathUrl = "http://51.25.255.88:32096/ifaas-authority/oauth/token";
//            String token = "Basic c3VwZXJ1c2VyOjEyMzQ1Ng==";
//            String username = "xjgaadmin";
//            String password = "53e85fb396587353fba0e1d0ba5f5e6b";
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("text/plain");
            MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", username).addFormDataPart("password", password)
                    .addFormDataPart("scope", "read write").addFormDataPart("grant_type", "password").build();
            Request request = new Request.Builder().url(tokenUrl).method("POST", body).addHeader("token", tokenDefalt)
                    .build();
            Response response = client.newCall(request).execute();
            System.out.println("response结果====" + response);
            res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().setCode(200).setData(res).setMassage("获取token成功");

    }

    public String getCollectList(CollectParamsDto collectParamsDto) {
//        String pathUrl = "http://127.0.0.1:32096/deep/collectList";
        String result = "";
        try {
            /*获取token，调用公共方法*/
            String token = tokenPublicVoid();
            log.info(">>>>获取token成功,值为{}", token);
            /*封装json*/
            Map<String, Object> params = new HashMap<>();
            params.put("sourceId", collectParamsDto.getSourceId());
            params.put("page", collectParamsDto.getPage());
            params.put("pageSize", collectParamsDto.getPageSize());
            params.put("access_token", token);
            params.put("sequence", collectParamsDto.getSequence());
            params.put("partitionId", collectParamsDto.getPartitionId());
            if (!StringUtils.isNullOrEmpty(collectParamsDto.getTargetType())) {
                params.put("targetType", collectParamsDto.getTargetType());
            }
            if (!StringUtils.isNullOrEmpty(collectParamsDto.getRelative())) {
                params.put("relative", collectParamsDto.getRelative());
            }
            /*params.put("relative","body" )*/
            List<String> timeList = collectParamsDto.getTimeList();
            String arr[] = timeList.toArray(new String[timeList.size()]);
            /*时间格式数组 String arr[] = {"2024-04-10 12:30:33","2024-05-13 12:30:30"};*/
            params.put("db_insert_time", arr);
            JSONObject jsonObjectData = new JSONObject();
            String jsonData = jsonObjectData.toJSONString(params);
            result = httpPostAndGetUtil.postJson(CollectDataUrl, jsonData, "POST", null);
        } catch (Exception e) {
            log.error("getCollectList接口调用深海数据异常,异常为:{}", e.toString());
            e.printStackTrace();
        }
        return result;
    }

    public void postUrls(List<People> peopleList) {
        JSONArray jsonArray = new JSONArray();
        List<Photo> photoList = new ArrayList<>();
        peopleList.forEach(people -> {
            String id = people.getId();
            String bigUrl = people.getBigUrl();
            String smallUrl = people.getSmallUrl();
            String peoplePassSmallUrl = people.getPeoplePassSmallUrl();
            String carSmallUrl = people.getCarSmallUrl();
            if (!StringUtils.isNullOrEmpty(bigUrl)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", id);
                jsonObject.put("type", 1);
                jsonObject.put("beforeUrl", bigUrl);
                jsonArray.add(jsonObject);

                Photo photo = new Photo();
                photo.setId(UUID.randomUUID().toString().substring(7));
                photo.setGuid(people.getFromImageId());
                photo.setBeforeUrl(bigUrl);
                photo.setDown(0);
                photo.setType(1);
                photoList.add(photo);
            }
            if (!StringUtils.isNullOrEmpty(smallUrl)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", id);
                jsonObject.put("type", 2);
                jsonObject.put("beforeUrl", smallUrl);
                jsonArray.add(jsonObject);

                Photo photo = new Photo();
                photo.setId(UUID.randomUUID().toString().substring(7));
                photo.setGuid(people.getId());
                photo.setBeforeUrl(smallUrl);
                photo.setDown(0);
                photo.setType(2);
                photoList.add(photo);
            }
            if (!StringUtils.isNullOrEmpty(peoplePassSmallUrl)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", id);
                jsonObject.put("type", 3);
                jsonObject.put("beforeUrl", peoplePassSmallUrl);
                jsonArray.add(jsonObject);

                Photo photo = new Photo();
                photo.setId(UUID.randomUUID().toString().substring(7));
                photo.setGuid(people.getPeoplePassId());
                photo.setBeforeUrl(peoplePassSmallUrl);
                photo.setDown(0);
                photo.setType(3);
                photoList.add(photo);
            }
            if (!StringUtils.isNullOrEmpty(carSmallUrl)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", id);
                jsonObject.put("type", 4);
                jsonObject.put("beforeUrl", carSmallUrl);
                jsonArray.add(jsonObject);

                Photo photo = new Photo();
                photo.setId(UUID.randomUUID().toString().substring(7));
                photo.setGuid(people.getCarId());
                photo.setBeforeUrl(carSmallUrl);
                photo.setDown(0);
                photo.setType(4);
                photoList.add(photo);
            }
        });
        boolean b = photoService.saveBatch(photoList);
        if (b) {
            log.info("photoList存库成功");
            /*将所有图片传给接口*/
            httpPostAndGetUtil.postJson(photoUrl, jsonArray.toJSONString(), "POST", null);
        } else {
            log.error("photoList存库失败");
        }

    }

    /*公共从redis中获取token方法。深海每个接口都需要调用这个 ，获取DeepToken的值*/
    public String tokenPublicVoid() {
        String token = "";
        try {
            long deepTokenLong = redisUtils.getExpire("access_token");
            if (deepTokenLong == -2 || deepTokenLong == -1) {
                Result result = getToken();
                String str = result.getData().toString();
                JSONObject jsonObject = JSON.parseObject(str);
                token = jsonObject.get("access_token").toString();
                Long expires_in = Long.valueOf(jsonObject.get("expires_in").toString());
                redisUtils.set("access_token", token, expires_in);
            } else {
                token = redisUtils.get("access_token").toString();
            }
        } catch (Exception e) {
            log.info("getToken()方法异常", e);
        }
        return token;
    }

    public Result getNodeToken() throws IOException {
        String token = "";
        String pathUrl = "http://127.0.0.1:32096/deep/token";
        try {
            String result = okhttpUtil.post(pathUrl, null, null);
////            System.out.println("获取接口返回的的token结果值==="+tokenRes);
//            String result = httpPostAndGetUtil.postJson(pathUrl, null, "POST", null);
            System.out.println("获取token接口返回的result的结果值===" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String access_token = jsonObject.get("access_token").toString();
            System.out.println("获取接口返回access_token===" + access_token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().setCode(200).setData(token);
    }

    public String ceShiCollectList() {
        String url = "http://51.25.255.88:32096/ifaas-collection/collection/api/analyze/resource/result/list/1.0";
        String token = "Bearer " + tokenPublicVoid();

        JSONObject jsonObjectParams = new JSONObject();
        /*andBean*/
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("field", "db_insert_time");
        jsonObject1.put("operator", "GTE");
        jsonObject1.put("value", "2024-04-10 12:30:33");
        jsonArray.add(jsonObject1);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("field", "db_insert_time");
        jsonObject2.put("operator", "LTE");
        jsonObject2.put("value", "2025-04-10 12:30:33");
        jsonArray.add(jsonObject2);

        JSONObject jsonObject4 = new JSONObject();
        jsonObject4.put("field", "pageNo");
        jsonObject4.put("operator", "EQ");
        jsonObject4.put("value", 1);
        jsonArray.add(jsonObject4);

        JSONObject jsonObject5 = new JSONObject();
        jsonObject5.put("field", "pageSize");
        jsonObject5.put("operator", "EQ");
        jsonObject5.put("value", 300);
        jsonArray.add(jsonObject5);

        JSONObject jsonObject6 = new JSONObject();
        jsonObject6.put("field", "operator");
        jsonObject6.put("operator", "EQ");
        jsonObject6.put("value", "ifass-engine");
        jsonArray.add(jsonObject6);

        JSONObject jsonObject7 = new JSONObject();
        jsonObject7.put("field", "targetType");
        jsonObject7.put("operator", "EQ");
        jsonObject7.put("value", "face");
        jsonArray.add(jsonObject7);


        /*orBeanList*/
        JSONArray jsonArrayOrBeanList = new JSONArray();
        JSONObject jsonObject8 = new JSONObject();
        jsonObject8.put("field", "sourceId");
        jsonObject8.put("operator", "EQ");
        jsonObject8.put("value", "10174");
        jsonArrayOrBeanList.add(jsonObject8);

        JSONObject jsonObject9 = new JSONObject();
        jsonObject9.put("field", "sourceType");
        jsonObject9.put("operator", "EQ");
        jsonObject9.put("value", "hikCamera");
        jsonArrayOrBeanList.add(jsonObject9);
        JSONArray jsonArrayParent = new JSONArray();
        JSONArray jsonArrayChildren = new JSONArray();
        jsonArrayParent.add(jsonArrayChildren);
        jsonArrayChildren.add(jsonArrayOrBeanList);

        jsonObjectParams.put("orBeanList", jsonArrayParent);
        jsonObjectParams.put("andBean", jsonArray);
        jsonObjectParams.put("sort", "desc");
        jsonObjectParams.put("relative", false);
        jsonObjectParams.put("needTotal", false);
        System.out.println(jsonObjectParams.toJSONString());

        String postResult = httpPostAndGetUtil.postJson(url, jsonObjectParams.toJSONString(), "POST", token);
        System.out.println("postResult===" + postResult);
        return postResult;
    }


}
